<template>
  <el-card>
    <div class="basic-content">
      <div class="flex items-center">
        <el-icon size="22" class="mr-[10px]"><Tickets /></el-icon>
        <el-text size="large" class="font-bold">补充认证材料</el-text>
      </div>
      <div class="py-[16px] font-14">企业基本信息</div>
      <el-form
        ref="ruleFormRef"
        label-position="top"
        :model="ruleForm"
        :rules="rules"
        class="basic-form"
        label-width="auto"
      >
        <el-form-item label="企业名称" prop="companyName" disabled>
          <el-input
            v-model="ruleForm.companyName"
            placeholder="请输入企业名称"
          />
        </el-form-item>

        <el-form-item label="社会统一信用代码" prop="creditCode" disabled>
          <el-input
            v-model="ruleForm.creditCode"
            placeholder="请输入社会统一信用代码"
          />
        </el-form-item>

        <el-form-item label="营业执照有效期" prop="validity" disabled>
          <el-input
            v-model="ruleForm.validity"
            placeholder="请输入营业执照有效期"
          />
        </el-form-item>

        <el-form-item label="注册资金" prop="capita">
          <el-input v-model="ruleForm.capita" placeholder="请输入注册资金" />
        </el-form-item>

        <el-form-item label="经营地址" prop="address">
          <el-input
            v-model="ruleForm.address"
            type="textarea"
            placeholder="请输入经营地址"
          />
        </el-form-item>

        <el-form-item label="经营范围描述" prop="busScope">
          <el-input
            v-model="ruleForm.busScope"
            type="textarea"
            placeholder="请输入经营范围描述"
          />
        </el-form-item>

        <el-form-item prop="license" label="*其他证明材料" class="upload-item">
          <el-upload
            class="upload-demo"
            drag
            action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15"
            :show-file-list="false"
            :on-change="handleAvatarChange"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            :limit="1"
            accept="image/png, image/jpeg, image/jpg"
            multiple
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <div v-else>
              <el-icon class="el-icon--upload"><upload-filled /></el-icon>
              <div class="el-upload__text">
                <el-text size="large" type="primary">*其他证明材料</el-text>
                <el-text size="small"
                  >JPG、PNG、PDF 文件，单个最大 10MB，最多 5个文件</el-text
                >
              </div>
            </div>
          </el-upload>
        </el-form-item>

        <el-form-item class="upload-item">
          <div class="w-full flex justify-center">
            <el-button class="w-[100px]" @click="backFollow">
              返回审核进度
            </el-button>

            <el-button class="w-[100px]" type="primary" @click="supplement">
              提交补充材料
            </el-button>
          </div>
        </el-form-item>
      </el-form>
    </div>
  </el-card>
</template>

<script lang="ts" setup>
import { reactive, ref } from "vue";
import { useRouter } from "vue-router";
import { MoreFilled, Tickets } from "@element-plus/icons-vue";
import { UploadFilled } from "@element-plus/icons-vue";
import type { FormInstance, FormRules } from "element-plus";
import type { UploadProps } from "element-plus";
import { message } from "@/utils/message";
import { ElMessage, ElMessageBox } from "element-plus";
import type { Action } from "element-plus";
const router = useRouter();
interface RuleForm {
  companyName: string;
  creditCode: string;
  companyShortName: string;
  merchantType: string;
  validity: string;
  address: string;
  industryType: string;
  capita: string;
  beneficiary: string;
  website: string;
  busScope: string;
}

const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive<RuleForm>({
  companyName: "",
  creditCode: "",
  companyShortName: "",
  merchantType: "",
  validity: "",
  address: "",
  industryType: "",
  capita: "",
  beneficiary: "",
  website: "",
  busScope: ""
});
const imageUrl = ref("");
const options = reactive([
  { label: "服装鞋帽", value: 1 },
  { label: "电子产品", value: 2 },
  { label: "美妆", value: 3 },
  { label: "食品饮料", value: 4 },
  { label: "母婴家居", value: 5 }
]);

const locationOptions = ["Home", "Company", "School"];

const rules = reactive<FormRules<RuleForm>>({
  companyName: [
    { required: true, message: "请输入企业名称", trigger: "blur" },
    { min: 1, max: 100, message: "企业名称不得超过100个字符", trigger: "blur" }
  ],
  creditCode: [
    { required: true, message: "社会统一信用代码", trigger: "blur" },
    {
      min: 1,
      max: 18,
      message: "社会统一信用代码不得超过18个字符",
      trigger: "blur"
    }
  ],
  companyShortName: [
    { required: true, message: "请输入企业简称", trigger: "blur" },
    { min: 1, max: 50, message: "企业简称不得超过100个字符", trigger: "blur" }
  ],
  merchantType: [
    { required: true, message: "请选择商户属性", trigger: "change" }
  ],
  validity: [
    { required: true, message: "请输入营业执照有效期", trigger: "blur" }
  ],
  address: [
    { required: true, message: "请输入经营地址", trigger: "blur" },
    { min: 1, max: 200, message: "经营地址不得超过200个字符", trigger: "blur" }
  ],

  industryType: [
    { required: true, message: "请选择类目/行业分类", trigger: "change" }
  ],

  capita: [
    { required: true, message: "请输入注册资金", trigger: "blur" },
    { min: 1, max: 11, message: "不得超过11个字符", trigger: "blur" }
  ],

  beneficiary: [
    { required: true, message: "请输入受益所有人", trigger: "blur" },
    { min: 1, max: 50, message: "不得超过50个字符", trigger: "blur" }
  ],

  website: [
    {
      required: true,
      message: "请输入企业网站/APP/公众号/小程序",
      trigger: "blur"
    },
    { min: 1, max: 200, message: "不得超过200个字符", trigger: "blur" }
  ],
  busScope: [
    { required: true, message: "请输入经营范围描述", trigger: "blur" },
    { min: 1, max: 500, message: "不得超过500个字符", trigger: "blur" }
  ]
});

const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  // 优先使用 raw 文件，如果没有则使用 url
  if (uploadFile.raw) {
    imageUrl.value = URL.createObjectURL(uploadFile.raw);
  } else if (uploadFile.url) {
    imageUrl.value = uploadFile.url;
  }
};

const handleAvatarChange: UploadProps["onChange"] = (response, uploadFile) => {
  // 优先使用 raw 文件，如果没有则使用 url
  if (uploadFile.raw) {
    imageUrl.value = URL.createObjectURL(uploadFile.raw);
  } else if (uploadFile.url) {
    imageUrl.value = uploadFile.url;
  }
};

const beforeAvatarUpload: UploadProps["beforeUpload"] = rawFile => {
  console.log("beforeUpload triggered:", rawFile);

  const fileType = ["image/png", "image/jpeg", "image/jpg"];
  if (!fileType.includes(rawFile.type)) {
    message("上传的图片只能是 JPG, PNG, JPEG格式", { type: "warning" });
    return false;
  } else if (rawFile.size / 1024 / 1024 > 5) {
    message("上传的图片必须小于5M", { type: "warning" });
    return false;
  }
  // 直接在这里创建 URL，确保有文件对象
  imageUrl.value = URL.createObjectURL(rawFile);
  return true;
};

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log("submit!");
    } else {
      console.log("error submit!", fields);
    }
  });
};

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};

const backFollow = () => {
  router.push("/application/follow");
};

const supplement = () => {
  ElMessageBox.alert("补充材料已提交成功，我们将尽快审核。", "提示", {
    confirmButtonText: "OK",
    center: true,
    callback: (action: Action) => {
      // ElMessage({
      //   type: "info",
      //   message: `action: ${action}`
      // });
    }
  });
};
</script>

<style lang="scss" scoped>
.basic-form {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  .el-form-item {
    width: 48%;
    margin-bottom: 20px;
  }
  .upload-item {
    width: 100%;
  }
  .upload-demo {
    width: 100%;
    .el-upload__text {
      display: flex;
      flex-direction: column;
    }
    .avatar {
      height: 100px;
    }
  }
}
</style>
